import sql from 'mssql' // 引入mssql连接SQLSever数据库类库
import conf from '../../config' // 引入配置文件
let closeTimer = null // 定义关闭连接池定时器

/**
 * 封装连接SQLSever数据库类
 */
class MssqlConnect {
  constructor() {
    this.connections = {} // 连接库装载对象
  }

  /**
   * 使用数据库
   * @param {String} database 
   * return 返回相关操作方法 
   */
  use(database) {
    // 如果存在选择库则用新的库
    const config = Object.assign(conf.db, {
      database: database || 'manke'
    })

    // 获得连接数据库Promise
    const promise = this._promise(config)
    return {

      /**
       * 查询数据库方法
       * @param {String} sql 查询数据库操作语句
       * @param {Object} inputs 定义输入对象
       */
      query: (sql, inputs) => {
        return promise.then((conn) => {
          let result = null
          let chain = conn.request();
          if (inputs) {
            for (let i in inputs) {
              if (inputs.hasOwnProperty(i)) {
                chain = chain.input(i, inputs[i])
              }
            }
          }
          result = chain.query(sql)
          return result
        })
      },
      execute: (store, inputs) => {
        return promise.then((conn) => {
          let result = null
          let chain = conn.request();
          if (inputs) {
            for (let i in inputs) {
              if (inputs.hasOwnProperty(i)) {
                chain = chain.input(i, inputs[i])
              }
            }
          }
          result = chain.query(store);
          return result
        })
      }
    }
  }

  /**
   * 关闭数据库连接
   */
  close() {
    let args = arguments;
    if (closeTimer) {
      clearTimeout(closeTimer);
      closeTimer = null
    }
    closeTimer = setTimeout(() => {
      if (args.length) {
        let names = Array.prototype.slice.call(args, 0);
        names.forEach(this._closeConn)
      } else {
        for (let i in this.connections) {
          this._closeConn(i)
        }
      }
    }, 3000)
  }

  // 关闭连接
  _closeConn(database) {
    let conn = this.connections[database]
    if (conn) {
      delete this.connections[database]
      if (conn.pool.connected) {
        // console.log(`已经关闭连接: ${database}`)
        conn.pool.close()
      } else if (conn.pool.connecting) {
        // console.log(`关闭连接: ${database}`)
      }
    }
  }

  /**
   * _promise连接池Promise
   * @param {Object} config 数据连接配置
   */
  _promise(config) {
    let _this = this
    let connections = _this.connections
    const database = config.database
    let conn = connections[database]
    // console.log(`连接数据库 ${Object.keys(connections).join(',')}`)
    return new Promise((resolve, reject) => {
      if (!conn) {
        conn = connections[database] = {
          pool: new sql.ConnectionPool(config)
        }
        conn.promise = conn.pool.connect()
      }
      // console.log(`连接数据库表${database}: ${conn.pool.config.database} connected=${conn.pool.connected} connecting=${conn.pool.connecting}`)
      if (conn.pool.connected) {
        // console.log('数据库连接成功！')
        resolve(conn.pool)
      } else if (conn.pool.connecting) {
        // console.log('数据库连接中…')
        conn.promise.then(() => {
          resolve(conn.pool)
        })
      } else {
        // console.log('数据库连接失败！')
        reject(conn.pool)
      }
    })
  }
}

// 将连接数据库实例导出
export default new MssqlConnect()
